<template>
  <div>
    <textarea v-model="text" @input="countWordFrequency" placeholder="Enter text here"></textarea>
    <div v-if="Object.keys(sortedWordFrequency).length">
      <h2>Top 3 Word Frequency:</h2>
      <ul>
        <li v-for="(count, word) in sortedWordFrequency" :key="word">
          {{ word }}: {{ count }}
          <span v-if="adjacentFrequency[word]">
            , left: {{ adjacentFrequency[word].leftWord }} ({{ adjacentFrequency[word].leftCount }}),
            right: {{ adjacentFrequency[word].rightWord }} ({{ adjacentFrequency[word].rightCount }})
          </span>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      text: '',
      wordFrequency: {},
      sortedWordFrequency: {},
      adjacentFrequency: {}
    }
  },
  methods: {
    countWordFrequency() {
      const words = this.text.toLowerCase().match(/\b\w+\b/g);
      const frequencyMap = {};
      const adjacentMap = {};

      if (words) {
        for (let i = 0; i < words.length; i++) {
          const word = words[i];
          frequencyMap[word] = (frequencyMap[word] || 0) + 1;
          if (i > 0) {
            const prevWord = words[i - 1];
            adjacentMap[word] = adjacentMap[word] || {};
            adjacentMap[word].leftWord = prevWord;
            adjacentMap[word].leftCount = (adjacentMap[word].leftCount || 0) + 1;
            adjacentMap[prevWord] = adjacentMap[prevWord] || {};
            adjacentMap[prevWord].rightWord = word;
            adjacentMap[prevWord].rightCount = (adjacentMap[prevWord].rightCount || 0) + 1;
          }
        }
      }

      const sortedFrequency = Object.entries(frequencyMap)
        .sort((a, b) => b[1] - a[1])
        .slice(0, 3);

      this.sortedWordFrequency = Object.fromEntries(sortedFrequency);

      const topWords = sortedFrequency.map(entry => entry[0]);
      topWords.forEach(word => {
        const leftAdjacentWord = adjacentMap[word]?.leftWord || '';
        const rightAdjacentWord = adjacentMap[word]?.rightWord || '';
        this.adjacentFrequency[word] = {
          leftWord: leftAdjacentWord,
          leftCount: adjacentMap[leftAdjacentWord]?.rightCount || 0,
          rightWord: rightAdjacentWord,
          rightCount: adjacentMap[rightAdjacentWord]?.leftCount || 0
        };
      });

      this.wordFrequency = frequencyMap;
    }
  }
}
</script>

<style scoped>
textarea {
  width: 100%;
  height: 200px;
  margin-bottom: 10px;
}
</style>